<template>
	<view class="h-fill">
		<view v-if="list.length">
			<view v-for="(item, idx) in list" :key="item.id" class="order-item round-corner pad">
				<view @click="navToOrderDetail(idx)" class="uni-flex align-center">
					<image class="icon-time" src="https://7463-tcb-zoumbaexjdidjmj2ff212-5d3479-1303238310.tcb.qcloud.la/static/img/ic_shijian.png" mode="widthFix"></image>
					<text class="uni-flex-extend uni-bold">{{item.createTime || '-'}}</text>
					<text :style="{color: orderStatus[item.status + ''].color}">{{orderStatus[item.status + ""].label}}</text>
				</view>
				<view @click="navToOrderDetail(idx)" class="t-pad b-pad">
					<view class="uni-flex">
						<view v-if="item.orderItemList && item.orderItemList.length && item.orderItemList[0].productPic" class="goods-img">
							<u-lazy-load :borderRadius="20" loading-img="/static/easy-loadimage/loading.gif"
								error-img="/static/img/img_home_quesheng@2x.png" 
								:image="item.orderItemList[0].productPic" :height="128" img-mode="aspectFill"></u-lazy-load>
						</view>
						<view v-else class="goods-img">
							<image class="h-fill v-fill" :src="$getCloudStorageUrl('/img_home_quesheng_no_bg@2x.png')" mode="aspectFit"></image>
						</view>
						<text class="uni-flex-extend uni-bold">{{item.orderItemList[0].productName}}</text>
						<view class="uni-flex uni-column align-end">
							<text class="uni-bold">￥{{item.orderItemList[0].productPrice || '-'}}</text>
							<text class="uni-text-gray">x{{item.orderItemList[0].productQuantity || '-'}}</text>
						</view>
					</view>
				</view>
				<view class="uni-flex align-center">
					<text class="uni-flex-extend uni-text-gray uni-text-small">订单编号：{{item.orderSn}}</text>
					<!-- #ifndef H5 -->
					<u-button @click="handleCopy(item)" shape="circle" size="mini">复制</u-button>
					<!-- #endif -->
				</view>
				<view class="t-pad b-pad">
					<u-line color="#EAEAEA"></u-line>
				</view>
				<view class="uni-flex justify-end">
					<view v-if="item.status === 0">
						<u-button @click="handlePay(item)" type="error" shape="circle">立即支付</u-button>
					</view>
					<view v-if="item.groupId && item.status !== 13 && item.status !== 14">
						<u-button @click="navToGroupDetail(item)" type="error" shape="circle">查看拼团</u-button>
					</view>
				</view>
			</view>
			<uni-load-more :status="loadingStatus"></uni-load-more>
		</view>
		<view v-else class="pad">
			<u-empty></u-empty>
		</view>
		<request-notify-wx ref="requestNotifyWx" :templates="templates"></request-notify-wx>
	</view>
</template>

<script>
	import {orderStatus} from "../../common/constants.js"
	export default {
		data() {
			return {
				orderStatus,
				list: [],
				pageNum: 0,
				pageSize: 20,
				loadingStatus: 'noMore',
				templates: [{
					templateName: "拼团结果提醒",
					templateId: "yNidF1PvZYWTofax_BzEIDPBeGoxDBjOU7RQNBxHGeE"
				}],
			};
		},
		props: {
			status: {
				type: Number,
				default: -1
			}
		},
		methods: {
			navToOrderDetail(idx) {
				// let item = this.list[idx];
				// console.log("navToOrderDetail", item);
				// uni.navigateTo({
				// 	url: "/pagesGroup/order-detail?id=" + item.id
				// })
			},
			navToGroupDetail(item) {
				uni.navigateTo({
					url: `/pagesGroup/group-detail?groupId=${item.groupId}&groupMemberId=${item.groupMemberId}`
				})
			},
			handleCopy(item) {
				uni.setClipboardData({
				    data: item.orderSn,
				    success: function () {
				        uni.showToast({
				        	title: "已复制",
							icon: "none"
				        })
				    }
				});
			},
			async handlePay(item) {
				try{
					if (item.groupId) {
						let hasGrouping = await this.hasGrouping(item.groupId);
						if (hasGrouping) {
							return;
						}
					}
					this.payOrder(item);
				}catch(e){
					this.$log("支付遇到错误", e);
				}
			},
			async payOrder(item) {
				if (this.busy) {
					return;
				}
				this.busy = true;
				this.orderToPay = item;
				//#ifdef MP-WEIXIN
				if (item.groupId) {
					await this.$refs.requestNotifyWx.request(false);
				}
				//#endif
				var orderPayInfo;
				try{
					orderPayInfo = await this.$http.genOrderPayInfo(item.id);
				} catch(e){
					this.busy = false;
					this.$log("获取微信支付订单数据遇到错误", e);
					return;
				}
				uni.showLoading({
					mask: true,
					title: '检测支付环境'
				})
				uni.requestPayment({
					provider: 'wxpay',
					timeStamp: orderPayInfo.wxPayMpOrderResult.timeStamp,
					nonceStr: orderPayInfo.wxPayMpOrderResult.nonceStr,
					package: orderPayInfo.wxPayMpOrderResult.packageValue,
					signType: orderPayInfo.wxPayMpOrderResult.signType,
					paySign: orderPayInfo.wxPayMpOrderResult.paySign,
					success: (res) => {
						this.busy = false;
						uni.hideLoading()
						this.$log('支付成功。' + JSON.stringify(res))
						this.finishPay()
					},
					fail: (err) => {
						this.busy = false;
						uni.hideLoading()
						this.$log('用户取消支付。' + JSON.stringify(err))
						this.handlePayFailed("确定放弃支付吗？");
					}
				})
			},
			showFaildModal() {
				uni.showModal({
					title: "手速过慢，拼团已经结束了",
					showCancel: false,
					success: (res) => {
						this.reload();
					}
				})
			},
			async finishPay() {
				if (!this.orderToPay) {
					return;
				}
				try{
					this.orderToPay = await this.$http.queryOrderStatus(this.orderToPay.orderSn)
					if (this.orderToPay.status === 13 || this.orderToPay.status === 14) {
						//付款速度慢了，拼团已结束
						this.showFaildModal();
					} else if (this.orderToPay.status === 0) {
						this.handlePayFailed("支付没有成功，是否重新支付？");
					} else {
						if (this.orderToPay.groupId) {
							this.navToGroupDetail(this.orderToPay);
						} else {
							this.reload();
						}
					}
				} catch(e) {
					this.$log("error", e);
					this.askRetryPay();
				}
			},
			askRetryPay() {
				uni.showModal({
					title: "查询支付状态遇到错误，是否重试？",
					cancelText: "稍后查看",
					confirmText: "重试",
					success: (res) => {
						if (res.confirm) {
							this.finishPay();
						}
					}
				})
			},
			handlePayFailed(msg) {
				uni.showModal({
					title: msg,
					cancelText: "放弃",
					confirmText: "重新支付",
					success: (res) => {
						if (res.confirm) {
							this.handlePay(this.orderToPay);
						}
					}
				})
			},
			async hasGrouping(groupId) {
				try{
					let groupMember = await this.$http.getGroupMember(groupId);
					if (groupMember) {
						uni.showModal({
							title: "您正在参与此拼团",
							cancelText: "朕知道了",
							confirmText: "去查看",
							success: (res) => {
								if (res.confirm) {
									uni.navigateTo({
										url: `/pagesGroup/group-detail?&groupId=${groupId}&groupMemberId=${groupMember.id}`
									})
								}
							}
						})
						return true;
					}
					return false;
				}catch(e){
					this.$log("error", e);
					throw e
				}
			},
			//取消订单
			async cancelOrder(item) {
				//todo
			},
			async reload() {
				if (this.loadingStatus === "loading") {
					return;
				}
				this.list = [];
				this.pageNum = 0;
				this.loadingStatus = "more";
				await this.loadMore();
			},
			async loadMore() {
				if (this.loadingStatus === "loading" || this.loadingStatus === "noMore") {
					return;
				}
				let prevStatus = this.loadingStatus;
				this.loadingStatus = "loading";
				let query = {
					pageNum: this.pageNum + 1,
					pageSize: 20,
				}
				if (this.status !== -1) {
					query.status = this.status;
				}
				try{
					let res = await this.$http.getOrders(query);
					if (res.records.length) {
						this.pageNum += 1;
						this.list = this.list.concat(res.records);
					}
					if (this.list.length < res.total) {
						this.loadingStatus = "more";
					} else {
						this.loadingStatus = "noMore";
					}
				}catch(e){
					this.$log("加载第三空间订单列表遇到错误", e);
					this.loadingStatus = prevStatus;
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.order-item {
		background-color: #FFFFFF;
		.icon-time {
			width: 40rpx;
			height: 40rpx;
			margin-right: 8rpx;
		}
		.goods-img {
			width: 230rpx;
			height: 128rpx;
			background-color: #ececec;
			border-radius: 20rpx;
			margin-right: 20rpx;
		}
	}
	.order-item:not(:last-child) {
		margin-bottom: 20rpx;
	}
</style>
